package v1

import (
	"encoding/hex"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gutil"
	"strconv"
	"strings"
)

type Message struct {
	MSG_LENGTH       int64
	MSG_SN           int64
	MSG_ID           string
	MSG_GNSSCENTERID int64
	VERSION_FLAG1    int64
	VERSION_FLAG2    int64
	VERSION_FLAG3    int64
	VERSION_FLAG     string
	ENCRYPT_FLAG     int64
	ENCRYPT_KEY      int64
	VEHICLE_NO       []byte
	VEHICLE_COLOR    string
	DATA_TYPE        string
	DATALENG         int64
}

type InfoHead interface {
	decodeChat(info3 string) *Message
	CheckMessage(info3 string) bool
}

func (t *Message) decodeChat(info3 string) *Message {
	t.MSG_LENGTH, _ = strconv.ParseInt(info3[0:8], 16, 64)         //数据长度
	t.MSG_SN, _ = strconv.ParseInt(info3[8:16], 16, 64)            //报文序列号
	t.MSG_ID = info3[16:20]                                        //业务类型ID
	t.MSG_GNSSCENTERID, _ = strconv.ParseInt(info3[20:28], 16, 64) //下级平台接入码 	//下级平台接入码
	t.VERSION_FLAG1, _ = strconv.ParseInt(info3[28:30], 16, 64)
	t.VERSION_FLAG2, _ = strconv.ParseInt(info3[30:32], 16, 64)
	t.VERSION_FLAG3, _ = strconv.ParseInt(info3[32:34], 16, 64)
	t.VERSION_FLAG = strconv.FormatInt(t.VERSION_FLAG1, 10) + "." + strconv.FormatInt(t.VERSION_FLAG2, 10) + "." + strconv.FormatInt(t.VERSION_FLAG3, 10) //协议版本号
	t.ENCRYPT_FLAG, _ = strconv.ParseInt(info3[34:36], 16, 64)                                                                                            //报文加密识别
	t.ENCRYPT_KEY, _ = strconv.ParseInt(info3[36:44], 16, 64)                                                                                             //数据加密密钥
	t.VEHICLE_NO, _ = hex.DecodeString(info3[44:86])
	t.VEHICLE_COLOR = info3[86:88] //车牌颜色
	t.DATA_TYPE = info3[88:92]     //子业务类型
	t.DATALENG, _ = strconv.ParseInt(info3[92:100], 16, 64)
	//gutil.Dump(t)
	return t
}

//5b0000001f000000001002000c5b510000000001020f0000000000009cdf5d    538

func (t *Message) CheckMessage(info3 string) bool {
	t.MSG_LENGTH, _ = strconv.ParseInt(info3[0:8], 16, 64)
	if gvar.New(t.MSG_LENGTH).Int()*2 != len(info3)+4 {
		return false
	} else {
		return true
	}
}

func decode(strDecode string) {
	info3 := strDecode[2 : len(strDecode)-2]
	info3 = arrMake(info3)
	if len(info3) < 100 {
		return
	}
	if strDecode[0:2] == "5b" && strDecode[len(strDecode)-2:] == "5d" {
		strDecodeNew := strings.Replace(strDecode, "5d5b00", "5d,5b00", -1)
		strArray := strings.Split(strDecodeNew, ",")
		for _, v := range strArray {
			info3 = v
			info3 = info3[2 : len(v)-2]
			info3 = arrMake(info3)
			var InfoHead InfoHead = &Message{}
			if !InfoHead.CheckMessage(info3) {
				gutil.Dump("丢包了")
				_, err := g.DB().Model("fa_unknow").Data(g.Map{"text": v, "time": gtime.Timestamp(), "rank": info3, "len": len(info3) + 4}).Insert()
				if err != nil {
					glog.Error(ctx, err)
				}
			} else {
				DataSave(info3)
			}
		}

	} else {
		gutil.Dump("需要补包，已加入缓存")
		makeBag.Append(strDecode)
	}
	DataSave(info3)
}

func DataSave(info3 string) {
	lenEnd := len(info3)
	array := g.Map{}
	var infoHead InfoHead = &Message{}
	infoHead.decodeChat(info3)
	i := 100
	res := rec
	for _, v := range res {
		if (2*gvar.New(v["byte"]).Int())+i > lenEnd {
			break
		}
		arr, _ := hex.DecodeString(info3[i : (2*gvar.New(v["byte"]).Int())+i])
		i = (2 * gvar.New(v["byte"]).Int()) + i
		array[gvar.New(v["map"]).String()] = rmu0000(TestEncoder(string(arr)))
	}
	//gutil.Dump(array)
	_, err := g.DB().Model("fa_xjtcp").OmitEmpty().Data(array).Save()
	if err != nil {
		glog.Error(ctx, err)
	}
	return
}

func Supplement() {
	//var (
	//	ctx      = gctx.New()
	//	interval = time.Second
	//)
	//gtimer.AddSingleton(ctx, interval, func(ctx context.Context) {
	//	if makeBag.Len() > 1 {
	//		strDecode := gvar.New(makeBag.Get(0)).String() + gvar.New(makeBag.Get(1)).String()
	//		if strDecode[0:2] == "5b" && strDecode[len(strDecode)-2:] == "5d" {
	//			decode(strDecode)
	//			makeBag.Remove(0)
	//			makeBag.Remove(0)
	//			gutil.Dump("补包成功:包体长度为" + gvar.New(makeBag.Len()).String())
	//		} else {
	//			if strDecode[0:2] != "5b" {
	//				glog.Error(ctx, "头标识丢失，丢包了")
	//			}
	//			makeBag.Set(1, strDecode)
	//			makeBag.Remove(0)
	//		}
	//	}
	//})
	for {
		if makeBag.Len() > 1 {
			strDecode := gvar.New(makeBag.Get(0)).String() + gvar.New(makeBag.Get(1)).String()
			if strDecode[0:2] == "5b" && strDecode[len(strDecode)-2:] == "5d" {
				decode(strDecode)
				makeBag.Remove(0)
				makeBag.Remove(0)
				//gutil.Dump("补包成功:包体长度为" + gvar.New(makeBag.Len()).String())
			} else {
				if strDecode[0:2] != "5b" {
					glog.Error(ctx, "头标识丢失，丢包了")
				}
				makeBag.Set(1, strDecode)
				makeBag.Remove(0)
			}
		}
	}
	select {}
}
